// ajax请求
function request(conf){
	const abortObj = new AbortController();
	
	const isType = o=> Object.prototype.toString.call(o).match(/\[object\s([a-zA-Z0-9]+)\]/)[1].toLowerCase();
	
	const formatUrlSearch = url =>{
		let search = (url + '').match(/\?([^\?\#]+)/);
		if(!search) return {};
		search = search[1].split('&');
		
		const params = {};
		search.forEach(v=>{
			v = decodeURIComponent(v).split('=');
			if(v.length === 2)  params[v[0]] = v[1];
		})
		
		return params;
	}
	const formatObjToUrlSearch = (params, url) =>{
		if( !['array','object'].includes(isType(params))  || !Object.keys(params).length ) return url || '';
		const search = Object.entries(params).map(([k,v])=> `${ encodeURIComponent(k) }=${encodeURIComponent(v)}` ).join("&");
		if(!url) return search;
		
		url+='';
		const reg = /\?([^\?\#]+)/;
		
		return url.match(reg) ? url.replace( reg, s=>{
			const oParams = formatUrlSearch(url);
			return `?${formatObjToUrlSearch(oParams)}&${search}`;
		} ) : `${url}?${search}`;
	}
	
	
	let {url = '', baseUrl = '',  noMsg, method = 'post', data, params,  headers ={}, timeout = 0, resType = 'json', reqType = 'json'} = conf;
	const opt = {
		method: method.toUpperCase(),
		signal: abortObj.signal,
		...conf,
		headers:{
			"Content-Type": "application/json",
			...headers,
		},
		body: reqType === 'json' && ['object'].includes(isType(data)) ? JSON.stringify(data) : data,
	}
	
	Object.entries(opt.headers).forEach(([k,v])=> v === undefined && (delete opt.headers[k]) );
	
	
	timeout > 0 && setTimeout( abortObj.abort(), timeout);
	
	if(params) url = formatObjToUrlSearch( params, url)
	
	
	return fetch( url.match(/^(https?\:)?\/\// ) ? url : baseUrl + url  ,opt)
	.then(res=> resType ? res[resType]() : res )
	.then(res=>{
		if((!res || res.code !== 200) && !noMsg) alert( res.msg || '请求错误' );
		return resType === 'json' ? (res || {}) : res;
	})
	.catch( err => {
		if(!noMsg) alert(`出现错误：${err}, 请刷新重试`)
		return resType === 'json' ? {code: 'ERR'} : false;
	} )
}
// 验证是否登录
function verifLogin(){
	if(!this.userInfo) window.location.href = './sign.html';
}
// 获取日期
function getDate(type,dateObj){
	const repairZero = s=> (s+'').length === 1 ? '0' + s : s;
	dateObj = dateObj || new Date();
	const [date,time] = [
		`${dateObj.getFullYear()}-${repairZero(dateObj.getMonth() + 1 )}-${repairZero(dateObj.getDate())}`,
		`${repairZero(dateObj.getHours())}:${repairZero(dateObj.getMinutes())}:${repairZero(dateObj.getSeconds())}`
	]
	
	switch(type){
		case 'date': return date;
		case 'time': return time;
		default: return date + ' ' + time;
	}
}
 
// 退出
function logout(){
	window.localStorage.removeItem('userInfo');
	window.location.href = './sign.html';
}
// 跳转
function go(url,isRoute){
	window.location.href = url
}
function data(){
	return{
		loading:false,
		userInfo: JSON.parse(localStorage.getItem('userInfo') || 'null'),
	}
}
const config = { el:"#app", data, methods:{ logout,go,getDate,verifLogin } }
//登录
async function login(){
	const {acc,pwd} = this.form;
	if(!acc.match(/^[a-zA-Z0-9]{6,20}$/)) return alert('请输入正确的账号，由数字和字母组成，长度6位到20位')
	if(!pwd.match(/^[a-zA-Z0-9]{6,20}$/)) return alert('请输入正确的密码，由数字和字母组成，长度6位到20位')
	
	const res = await request({url:'/user/login',  data: this.form})
	if(res.code !== 200) return;
	
	alert('登录成功！')
	window.localStorage.setItem('userInfo', JSON.stringify(res.data));
	window.location.href = './personal.html';
}
//注册
async function reg(){
   const {acc,pwd,pwd2,name} = this.form;
   if(!acc.match(/^[a-zA-Z0-9]{6,20}$/)) return alert('请输入正确的账号，由数字和字母组成，长度6位到20位')
   if(!pwd.match(/^[a-zA-Z0-9]{6,20}$/)) return alert('请输入正确的密码，由数字和字母组成，长度6位到20位')
   if(pwd !== pwd2) return alert('2次密码不一致')
   if(!name) return alert('用户名不能为空')
   
   const res = await request({url:'/user/reg',  data: this.form})
   if(res.code !== 200) return;
   
   alert('注册成功，自动登录中...')
   setTimeout(()=> this.login(),100)
   
}

function data2(){
	return {
		userList: localStorage.userList && JSON.parse(localStorage.userList) || [],
		type:1,
		form:{
			name: '',
			acc: '',
			pwd: '',
			pwd2: '',
			
		}
		
	}
}


function pushNum(){
	return this.list.filter(v=> v.acc === this.userInfo.acc ).length;
}

function data3(){
	return {
		dialogShow:false,
		list: [],
		form:{
			content: '',
			title: '',
		},
	}
}